package com.zhang.common.security.handle;

import cn.hutool.core.util.CharsetUtil;
import com.alibaba.fastjson.JSONObject;

import com.zhang.common.core.constant.ResultConstant;
import com.zhang.common.core.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName AccessDeniedHandler
 * @Description
 * @Author
 * @Date 2019/10/28 14:24
 * @Version V1.0
 **/
@Slf4j
@Component
public class AccessDeniedHandler extends OAuth2AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException authException) throws IOException, ServletException {
        log.info("授权失败，禁止访问 {}", request.getRequestURI());
        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setContentType( MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter printWriter = response.getWriter();
        Result result = new Result(ResultConstant.EX_FORBIDDEN, StringUtils.isNotEmpty(authException.getMessage())?authException.getMessage():"拒绝访问!");
        printWriter.write(JSONObject.toJSONString(result));
        printWriter.flush();
    }
}